<template>
    <div class="dict-page">
        <div class="card-wrap mb10 animate-on-enter">
            <a-space wrap>
                <a-button type="primary" :icon="h(PlusCircleOutlined)" @click="onAddDictType">新增字典类型</a-button>
            </a-space>
        </div>
        <div class="card-wrap animate-on-enter animate-delay-1">
            <DataList ref="dictTypeListRef" :api="getDictTypes" :deleteApi="deleteDictType" :columns="dictTypeColumns"
                @action="handleDictTypeAction"></DataList>
        </div>



        <!-- 新增/编辑字典类型弹窗 -->
        <a-modal v-model:open="openDictTypeModal" :title="dictTypeFormState.id ? '编辑字典类型' : '新增字典类型'"
            :maskClosable="false" :footer="null">
            <a-form ref="dictTypeFormRef" :model="dictTypeFormState" :label-col="labelCol" :rules="dictTypeRules"
                @finish="onDictTypeSubmit">
                <a-form-item label="字典名称" name="dict_name">
                    <a-input v-model:value="dictTypeFormState.dict_name" placeholder="请填写字典名称" />
                </a-form-item>
                <a-form-item label="字典类型" name="dict_type">
                    <a-input v-model:value="dictTypeFormState.dict_type" placeholder="请填写字典类型（英文字母、数字、下划线）"
                        :disabled="!!dictTypeFormState.id" />
                </a-form-item>
                <a-form-item label="状态" name="status">
                    <a-radio-group v-model:value="dictTypeFormState.status">
                        <a-radio :value="1">正常</a-radio>
                        <a-radio :value="0">停用</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label="备注" name="remark">
                    <a-textarea v-model:value="dictTypeFormState.remark" placeholder="请填写备注" :rows="3" />
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                    <a-button type="primary" html-type="submit" :loading="dictTypeSubmitLoading">保存</a-button>
                    <a-button style="margin-left: 10px" @click="openDictTypeModal = false">取消</a-button>
                </a-form-item>
            </a-form>
        </a-modal>

        <!-- 字典数据管理弹窗 -->
        <a-modal v-model:open="openDictDataModal" :title="`字典数据管理 - ${currentDictType?.dict_name || ''}`"
            width="1200px" :footer="null">
            <div class="dict-data-modal-content">
                <div class="modal-header">
                    <a-button type="primary" :icon="h(PlusCircleOutlined)" @click="onAddDictData">
                        新增字典数据
                    </a-button>
                </div>
                
                <a-table 
                    :columns="dictDataTableColumns" 
                    :data-source="dictDataList" 
                    :loading="dictDataLoading"
                    :pagination="showPagination ? dictDataPagination : false"
                    row-key="id"
                    size="middle">
                    
                    <!-- 字典标签列 -->
                    <template #bodyCell="{ column, record, index }">
                        <template v-if="column.dataIndex === 'dict_label'">
                            <a-input 
                                v-if="editingKey === record.id" 
                                v-model:value="record.dict_label" 
                                @pressEnter="saveEdit(record)"
                                @blur="saveEdit(record)"
                                style="margin: -5px 0" />
                            <span v-else>{{ record.dict_label }}</span>
                        </template>
                        
                        <!-- 字典键值列 -->
                        <template v-else-if="column.dataIndex === 'dict_value'">
                            <a-input 
                                v-if="editingKey === record.id" 
                                v-model:value="record.dict_value" 
                                @pressEnter="saveEdit(record)"
                                @blur="saveEdit(record)"
                                style="margin: -5px 0" />
                            <span v-else>{{ record.dict_value }}</span>
                        </template>
                        
                        <!-- 显示排序列 -->
                        <template v-else-if="column.dataIndex === 'dict_sort'">
                            <a-input-number 
                                v-if="editingKey === record.id" 
                                v-model:value="record.dict_sort" 
                                :min="0"
                                @pressEnter="saveEdit(record)"
                                @blur="saveEdit(record)"
                                style="margin: -5px 0; width: 100%" />
                            <span v-else>{{ record.dict_sort }}</span>
                        </template>
                        
                        <!-- 状态列 -->
                        <template v-else-if="column.dataIndex === 'status'">
                            <a-select 
                                v-if="editingKey === record.id" 
                                v-model:value="record.status" 
                                @change="saveEdit(record)"
                                style="margin: -5px 0; width: 100%">
                                <a-select-option :value="1">正常</a-select-option>
                                <a-select-option :value="0">停用</a-select-option>
                            </a-select>
                            <a-tag v-else :color="record.status === 1 ? 'green' : 'red'">
                                {{ record.status === 1 ? '正常' : '停用' }}
                            </a-tag>
                        </template>
                        
                        <!-- 是否默认列 -->
                        <template v-else-if="column.dataIndex === 'is_default'">
                            <a-select 
                                v-if="editingKey === record.id" 
                                v-model:value="record.is_default" 
                                @change="saveEdit(record)"
                                style="margin: -5px 0; width: 100%">
                                <a-select-option :value="1">是</a-select-option>
                                <a-select-option :value="0">否</a-select-option>
                            </a-select>
                            <a-tag v-else :color="record.is_default === 1 ? 'blue' : 'default'">
                                {{ record.is_default === 1 ? '是' : '否' }}
                            </a-tag>
                        </template>
                        
                        <!-- 备注列 -->
                        <template v-else-if="column.dataIndex === 'remark'">
                            <a-input 
                                v-if="editingKey === record.id" 
                                v-model:value="record.remark" 
                                @pressEnter="saveEdit(record)"
                                @blur="saveEdit(record)"
                                style="margin: -5px 0" />
                            <span v-else>{{ record.remark || '-' }}</span>
                        </template>
                        
                        <!-- 操作列 -->
                        <template v-else-if="column.key === 'action'">
                            <span v-if="editingKey === record.id">
                                <a @click="saveEdit(record)" style="margin-right: 8px" :class="{ 'ant-btn-loading': saveEditLoading }">保存</a>
                                <a @click="cancelEdit" :disabled="saveEditLoading">取消</a>
                            </span>
                            <span v-else>
                                <a @click="startEdit(record)" style="margin-right: 8px">编辑</a>
                                <a-popconfirm title="确定删除吗?" @confirm="deleteDictDataItem(record.id)">
                                    <a style="color: #ff4d4f">删除</a>
                                </a-popconfirm>
                            </span>
                        </template>
                    </template>
                </a-table>
            </div>
        </a-modal>

        <!-- 新增/编辑字典数据表单弹窗 -->
        <a-modal v-model:open="openDictDataFormModal" :title="dictDataFormState.id ? '编辑字典数据' : '新增字典数据'"
            :maskClosable="false" :footer="null">
            <a-form ref="dictDataFormRef" :model="dictDataFormState" :label-col="labelCol" :rules="dictDataRules"
                @finish="onDictDataSubmit">
                <a-form-item label="字典类型" name="dict_type">
                    <a-input v-model:value="dictDataFormState.dict_type" disabled />
                </a-form-item>
                <a-form-item label="数据标签" name="dict_label">
                    <a-input v-model:value="dictDataFormState.dict_label" placeholder="请填写数据标签" />
                </a-form-item>
                <a-form-item label="数据键值" name="dict_value">
                    <a-input v-model:value="dictDataFormState.dict_value" placeholder="请填写数据键值" />
                </a-form-item>
                <a-form-item label="显示排序" name="dict_sort">
                    <a-input-number v-model:value="dictDataFormState.dict_sort" placeholder="请填写显示排序" :min="0"
                        style="width: 100%" />
                </a-form-item>
                <a-form-item label="样式属性" name="css_class">
                    <a-input v-model:value="dictDataFormState.css_class" placeholder="请填写样式属性" />
                </a-form-item>
                <a-form-item label="表格样式" name="list_class">
                    <a-select v-model:value="dictDataFormState.list_class" placeholder="请选择表格样式">
                        <a-select-option value="default">默认</a-select-option>
                        <a-select-option value="primary">主要</a-select-option>
                        <a-select-option value="success">成功</a-select-option>
                        <a-select-option value="info">信息</a-select-option>
                        <a-select-option value="warning">警告</a-select-option>
                        <a-select-option value="danger">危险</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="是否默认" name="is_default">
                    <a-radio-group v-model:value="dictDataFormState.is_default">
                        <a-radio :value="1">是</a-radio>
                        <a-radio :value="0">否</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label="状态" name="status">
                    <a-radio-group v-model:value="dictDataFormState.status">
                        <a-radio :value="1">正常</a-radio>
                        <a-radio :value="0">停用</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label="备注" name="remark">
                    <a-textarea v-model:value="dictDataFormState.remark" placeholder="请填写备注" :rows="3" />
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                    <a-button type="primary" html-type="submit" :loading="dictDataSubmitLoading">保存</a-button>
                    <a-button style="margin-left: 10px" @click="openDictDataFormModal = false">取消</a-button>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script setup>
import { onMounted, ref, reactive, h } from 'vue';
import { message } from 'ant-design-vue';
import { PlusCircleOutlined } from '@ant-design/icons-vue';
import {
    getDictTypes,
    saveDictType,
    deleteDictType,
    getDictData,
    saveDictData,
    deleteDictData,
    getAllDictTypes
} from '@/api/dict.js';

/**
 * 页面全局变量
 */
// 字典类型表格列配置
const dictTypeColumns = [
    {
        title: '字典名称',
        dataIndex: 'dict_name'
    },
    {
        title: '字典类型',
        dataIndex: 'dict_type'
    },
    {
        title: '状态',
        dataIndex: 'status',
        customRender: ({ record }) => {
            return record.status === 1 ? '正常' : '停用';
        }
    },
    {
        title: '备注',
        dataIndex: 'remark'
    },
    {
        title: '创建时间',
        dataIndex: 'created_at'
    },
    {
        title: '操作',
        type: 'action',
        options: [
            {
                title: '字典数据',
                type: 'data'
            },
            {
                title: '编辑',
                type: 'edit'
            },
            {
                title: '删除',
                type: 'delete'
            }
        ]
    }
];

// 字典数据表格列配置
const dictDataTableColumns = [
    {
        title: '字典标签',
        dataIndex: 'dict_label',
        width: 150
    },
    {
        title: '字典键值',
        dataIndex: 'dict_value',
        width: 150
    },
    {
        title: '显示排序',
        dataIndex: 'dict_sort',
        width: 100
    },
    {
        title: '状态',
        dataIndex: 'status',
        width: 80
    },
    {
        title: '是否默认',
        dataIndex: 'is_default',
        width: 100
    },
    {
        title: '备注',
        dataIndex: 'remark',
        width: 200
    },
    {
        title: '创建时间',
        dataIndex: 'created_at',
        width: 180
    },
    {
        title: '操作',
        key: 'action',
        width: 120,
        fixed: 'right'
    }
];

// 表单相关
const labelCol = {
    style: {
        width: '70px',
    },
};
const dictTypeListRef = ref();
const dictTypeFormRef = ref();
const dictDataFormRef = ref();

// 字典类型相关状态
const openDictTypeModal = ref(false);
const dictTypeSubmitLoading = ref(false);
const dictTypeFormState = reactive({
    id: '',
    dict_name: '',
    dict_type: '',
    status: 1,
    remark: ''
});

// 字典数据相关状态
const openDictDataModal = ref(false);
const openDictDataFormModal = ref(false);
const dictDataSubmitLoading = ref(false);
const currentDictType = ref(null);
const dictDataFormState = reactive({
    id: '',
    dict_type: '',
    dict_label: '',
    dict_value: '',
    dict_sort: 0,
    css_class: '',
    list_class: 'default',
    is_default: 0,
    status: 1,
    remark: ''
});

// 字典数据表格相关状态
const dictDataList = ref([]);
const dictDataLoading = ref(false);
const dictDataPagination = ref({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
    onChange: (page, pageSize) => {
        dictDataPagination.value.current = page;
        dictDataPagination.value.pageSize = pageSize;
        loadDictDataList();
    },
    onShowSizeChange: (current, size) => {
        dictDataPagination.value.current = 1;
        dictDataPagination.value.pageSize = size;
        loadDictDataList();
    }
});
const showPagination = ref(true);

// 行内编辑相关状态
const editingKey = ref('');
const originalRecord = ref(null);
const saveEditLoading = ref(false);

// 字典类型选择
const dictTypeOptions = ref([]);

// 表单验证规则
const dictTypeRules = {
    dict_name: [
        {
            required: true,
            message: '请填写字典名称',
            trigger: 'change',
        },
        {
            max: 100,
            message: '字典名称不能超过100个字符',
            trigger: 'change',
        }
    ],
    dict_type: [
        {
            required: true,
            message: '请填写字典类型',
            trigger: 'change',
        },
        {
            max: 100,
            message: '字典类型不能超过100个字符',
            trigger: 'change',
        },
        {
            pattern: /^[a-zA-Z0-9_]+$/,
            message: '字典类型只能包含字母、数字和下划线',
            trigger: 'change',
        }
    ],
    status: [
        {
            required: true,
            message: '请选择状态',
            trigger: 'change',
        }
    ]
};

const dictDataRules = {
    dict_type: [
        {
            required: true,
            message: '请选择字典类型',
            trigger: 'change',
        }
    ],
    dict_label: [
        {
            required: true,
            message: '请填写数据标签',
            trigger: 'change',
        },
        {
            max: 100,
            message: '数据标签不能超过100个字符',
            trigger: 'change',
        }
    ],
    dict_value: [
        {
            required: true,
            message: '请填写数据键值',
            trigger: 'change',
        },
        {
            max: 100,
            message: '数据键值不能超过100个字符',
            trigger: 'change',
        }
    ],
    is_default: [
        {
            required: true,
            message: '请选择是否默认',
            trigger: 'change',
        }
    ],
    status: [
        {
            required: true,
            message: '请选择状态',
            trigger: 'change',
        }
    ]
};

/**
 * 页面生命周期
 */
onMounted(() => {
    loadDictTypes();
});

/**
 * 页面函数
 */

// 加载字典类型选项
const loadDictTypes = async () => {
    try {
        const res = await getAllDictTypes();
        if (res.code === 200) {
            dictTypeOptions.value = res.result;
        }
    } catch (error) {
        console.error('加载字典类型失败:', error);
    }
};

// 重置字典类型表单
function resetDictTypeForm() {
    dictTypeFormRef.value?.resetFields();
}

// 重置字典数据表单
function resetDictDataForm() {
    dictDataFormRef.value?.resetFields();
}

// 字典类型操作
const onAddDictType = () => {
    Object.assign(dictTypeFormState, {
        id: '',
        dict_name: '',
        dict_type: '',
        status: 1,
        remark: ''
    });
    resetDictTypeForm();
    openDictTypeModal.value = true;
};

const handleDictTypeAction = (item, record) => {
    const type = item.type;
    if (type === 'edit') {
        Object.assign(dictTypeFormState, record);
        openDictTypeModal.value = true;
    } else if (type === 'data') {
        currentDictType.value = record;
        openDictDataModal.value = true;
        // 重置分页并加载数据
        dictDataPagination.value.current = 1;
        loadDictDataList();
    }
};

// 加载字典数据列表
const loadDictDataList = async () => {
    if (!currentDictType.value?.dict_type) return;
    
    dictDataLoading.value = true;
    try {
        const params = {
            page: dictDataPagination.value.current,
            pageSize: dictDataPagination.value.pageSize,
            dict_type: currentDictType.value.dict_type
        };
        
        const res = await getDictData(params);
         if (res.code === 200) {
             dictDataList.value = res.result.list || [];
             const total = res.result.total || 0;
             
             // 如果只有一页数据，隐藏分页
             showPagination.value = total > dictDataPagination.value.pageSize;
             
             dictDataPagination.value.current = res.result.page || 1;
             dictDataPagination.value.total = total;
         }
    } catch (error) {
        console.error('加载字典数据失败:', error);
        message.error('加载字典数据失败');
    } finally {
        dictDataLoading.value = false;
    }
};

// 开始编辑
const startEdit = (record) => {
    editingKey.value = record.id;
    originalRecord.value = { ...record };
};

// 取消编辑
const cancelEdit = () => {
    if (originalRecord.value) {
        const index = dictDataList.value.findIndex(item => item.id === editingKey.value);
        if (index > -1) {
            dictDataList.value[index] = { ...originalRecord.value };
        }
    }
    editingKey.value = '';
    originalRecord.value = null;
};

// 保存编辑
const saveEdit = async (record) => {
    if (saveEditLoading.value) return; // 防止重复提交
    
    saveEditLoading.value = true;
    try {
        const res = await saveDictData(record);
        if (res.code === 200) {
            message.success('保存成功');
            editingKey.value = '';
            originalRecord.value = null;
            loadDictDataList();
        }
    } catch (error) {
        console.error('保存失败:', error);
        message.error('保存失败');
        cancelEdit();
    } finally {
        saveEditLoading.value = false;
    }
};

// 删除字典数据项
const deleteDictDataItem = async (id) => {
    try {
        const res = await deleteDictData({ id });
        if (res.code === 200) {
            message.success('删除成功');
            loadDictDataList();
        }
    } catch (error) {
        console.error('删除失败:', error);
        message.error('删除失败');
    }
};

const onDictTypeSubmit = async () => {
    dictTypeSubmitLoading.value = true;
    try {
        const res = await saveDictType(dictTypeFormState);
        if (res.code === 200) {
            message.success(res.message);
            openDictTypeModal.value = false;
            dictTypeListRef.value.refresh();
            loadDictTypes(); // 重新加载字典类型选项
        }
    } catch (error) {
        console.error('保存字典类型失败:', error);
        message.error('保存失败');
    } finally {
        dictTypeSubmitLoading.value = false;
    }
};

// 字典数据操作
const onAddDictData = () => {
    Object.assign(dictDataFormState, {
        id: '',
        dict_type: currentDictType.value?.dict_type || '',
        dict_label: '',
        dict_value: '',
        dict_sort: 0,
        css_class: '',
        list_class: 'default',
        is_default: 0,
        status: 1,
        remark: ''
    });
    resetDictDataForm();
    openDictDataFormModal.value = true;
};

const onDictDataSubmit = async () => {
    dictDataSubmitLoading.value = true;
    try {
        const res = await saveDictData(dictDataFormState);
        if (res.code === 200) {
            message.success(res.message);
            openDictDataFormModal.value = false;
            loadDictDataList();
        }
    } catch (error) {
        console.error('保存字典数据失败:', error);
        message.error('保存失败');
    } finally {
        dictDataSubmitLoading.value = false;
    }
};
</script>

<style lang="less" scoped></style>